<?php

namespace plugin\admin\app\controller;

use plugin\admin\app\model\IotDevice;
use Respect\Validation\Validator;
use support\exception\BusinessException;
use support\Request;
use support\Response;

/**
 * 设备管理
 */
class IotDeviceController extends Crud
{

    /**
     * @var IotDevice
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new IotDevice;
    }

    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('iot-device/index');
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $ip = $request->post('ip','');
            if ($ip){
                $v_ip = Validator ::ip()->setName('ip')->validate($ip);
                if (!$v_ip){
                    return errorMessage("ip验证失败");
                }
            }
            $port = $request->post('port','');
            if ($port){
                $v_port = Validator ::between(1,65535)->setName('端口')->validate($port);
                if (!$v_port){
                    return errorMessage("端口验证失败");
                }
            }
            if ($ip && $port){
                //判断端口是否已存在
                $exists = IotDevice::where('ip',$ip)->where('port',$port)->exists();
                if ($exists){
                    return errorMessage("ip+端口已存在");
                }
            }
            return parent::insert($request);
        }
        return view('iot-device/insert');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $ip = $request->post('ip','');
            if ($ip){
                $v_ip = Validator ::ip()->setName('ip')->validate($ip);
                if (!$v_ip){
                    return errorMessage("ip验证失败");
                }
            }
            $port = $request->post('port','');
            if ($port){
                $v_port = Validator ::between(1,65535)->setName('端口')->validate($port);
                if (!$v_port){
                    return errorMessage("端口验证失败");
                }
            }
            if ($ip && $port){
                //判断端口是否已存在
                $id = $request->post('id');
                $exists = IotDevice::where('ip',$ip)->where('id','<>',$id)->where('port',$port)->exists();
                if ($exists){
                    return errorMessage("ip+端口已存在");
                }
            }
            return parent::update($request);
        }
        return view('iot-device/update');
    }

    use \plugin\admin\app\traits\IotDevice;

}
